package com.eipc;

import java.util.ArrayList;
import java.util.Locale;
import org.androidpn.sdk.Constants;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.eipc.event.OnBarClickListener;
import com.eipc.event.OnFetchOtherFinishedListener;
import com.eipc.model.Game;
import com.eipc.model.News;
import com.eipc.model.Person;
import com.eipc.model.Weather;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.PreferencesHelper;
import com.eipc.util.Tools;
import com.eipc.view.Bar;
import com.eipc.view.BottomBar;

public abstract class CommonTabActivity extends TabActivity {
	protected static String currentActivity = null;
	private final static int PROMPT_ID = 0x000100;
	protected static String CONTROL_CENTER = "CONTROL_CENTER";
	protected static String MAIN = "MAIN";
	public final static String ACTION_POPUP_MESSAGE = "action.intent.popup.message";
	public final static int HANDLER_MESSAGE_POPUP = 1;
	public final static int HANDLER_MESSAGE_CLEAR =2;
	public static boolean isDialogShow = false;
	private Cursor mPopupCursor;
	protected Person mPerson;
	private PopupMessageBroadcast mReiceiver;
	private AudioManager mAudioManager;
	private NotificationManager mNotificationManager;
	private PreferencesHelper mHelper;
	protected int mLocale;         //当前的语言
	public long owerAct;
	protected String mReplyContent;
	protected String mReplyTime;
	protected String mInfoId;
	protected AlertDialog.Builder mBuilder;
	private long mInterval;    //二次弹出的间隔时间
	private Dialog mPopupDialog;
	private PushFinishBroadcast  mPushReceiver;
	private String mUrl;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		owerAct = System.currentTimeMillis();
		CommonActivity.CURRACT = owerAct;
		mRe = getResources();
		mDB = new DBHelper(this);
		mHelper = new PreferencesHelper(getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE));
		mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		mBuilder = new Builder(this).setTitle(R.string.tip);
		Resources res = getResources();
		Configuration cfg = res.getConfiguration();
		cfg.locale = getLocaleFromPreference();
		res.updateConfiguration(cfg, null);
	}
	
	private Locale getLocaleFromPreference(){
		mLocale = mHelper.getInt(CommonActivity.PERFERENCE_LANGUAGE);
		switch (mLocale) {
			case CommonActivity.LANGUAGE_CHINESE:
				return Locale.SIMPLIFIED_CHINESE;
			case CommonActivity.LANGUAGE_ENGLISH:
				return Locale.ENGLISH;
			default:
				return Locale.SIMPLIFIED_CHINESE;
		}
	}
	
	protected View buildLabel(int label){
    	LayoutInflater inflater = getLayoutInflater();
    	Button btn = (Button)inflater.inflate(R.layout.label, null);
    	btn.setText(label);
    	return btn;
    }

	protected void setCurrentActivity(String v) {
		currentActivity = v;
	}

	private void startReceiveMessage() {
		mReiceiver = new PopupMessageBroadcast();
		IntentFilter filter = new IntentFilter(ACTION_POPUP_MESSAGE);
		registerReceiver(mReiceiver, filter);
	}

	protected void doUpdateView(){
		if(isMyself()){
			Log.e("-----------isMyself begin updateView----------","update");
			updateView();
		}else{
			Log.e("-----------is not Myself dont updateView----------","do not update");
		}
	}
	
	public boolean isMyself(){
		return CommonActivity.CURRACT==owerAct?true:false;
	}
	
    protected void updateView(){
	}
	
	protected void startPush(){
		mPushReceiver = new PushFinishBroadcast();
		IntentFilter filter = new IntentFilter("action.push.finish");
		registerReceiver(mPushReceiver, filter);
	}
	
	protected void stopPush(){
		try {
			if(mPushReceiver!=null) unregisterReceiver(mPushReceiver);
		} catch (Exception e) {
		}
	}
	
	/*
	 * push结束广播
	 */
	class PushFinishBroadcast extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			mHandler.sendEmptyMessage(CommonActivity.HANDLER_MESSAGE_UPDATE_VIEW);
		}
	}
	
	protected Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case HANDLER_MESSAGE_POPUP:
					mPopupCursor = mDB.queryAll(DBHelper.TB_IMPORT_NOTICE,new String[] { DBHelper.FIELD_IMPORT_NOTICE_ID},new String[] {((Integer)msg.obj).toString()});
					showDailog(mPopupCursor);
					mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_CLEAR, 1*1000);
					break;
				case HANDLER_MESSAGE_CLEAR:
					mNotificationManager.cancel(PROMPT_ID);
					break;
				case CommonActivity.HANDLER_MESSAGE_UPDATE_VIEW:
					doUpdateView();
					break;
			}
		};
	};

	class PopupMessageBroadcast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent!=null){
				long current = System.currentTimeMillis();
				if((mInterval==0 || current - mInterval>CommonActivity.MAX_INTERVAL)&&(mPopupDialog==null ||(!mPopupDialog.isShowing()))){
					Integer id = intent.getIntExtra("id",0);
					if(id!=null && id!=0){
						mHandler.sendMessage(mHandler.obtainMessage(HANDLER_MESSAGE_POPUP, id));
						mInterval = current; 
					}
				}
				else{
					mInterval = current; 
				}
			}
		}
	}
	
	/*
	 * 显示图片
	 */
	private void showPicture(boolean isOk,Bitmap bm){
		if(isOk){
			final Dialog dialog = new Dialog(this);
			dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			View view = getLayoutInflater().inflate(R.layout.picture_dialog, null);
			ImageView iv = (ImageView)view.findViewById(R.id.iv_picture);
			iv.setImageBitmap(bm);
			dialog.setContentView(view);
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		}
	}

	private void showDailog(final Cursor info) {
		if (info != null && info.getCount() > 0 &&!isDialogShow) {
			info.moveToFirst();
			mPopupDialog = new Dialog(this);
			mPopupDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			mPopupDialog.setCancelable(false);
			View view = getLayoutInflater().inflate(
					R.layout.control_center_dialog, null);
			TextView tv = (TextView) view.findViewById(R.id.content);
			tv.setText(info.getString(info
					.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_CONTENT)));
			final int type = info.getInt(info.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_APPTYPE));
			TextView titleView = (TextView)view.findViewById(R.id.dialog_title);
			switch(type){
				case DBHelper.APP_TYPE_IMPORT_NOTICE://重要通知
					titleView.setText(getString(R.string.dialog_import_notice_title,getString(R.string.import_notice)));
					break;
				case DBHelper.APP_TYPE_ME_REPORT://我要找茬
					titleView.setText(getString(R.string.dialog_import_notice_title,getString(R.string.me_report)));
					break;
				case DBHelper.APP_TYPE_WORK_REPORT://工作汇报
					titleView.setText(getString(R.string.dialog_import_notice_title,getString(R.string.work_report)));
					break;
			}
			tv = (TextView) view.findViewById(R.id.issuer);
			tv.setText(Html.fromHtml(mRe.getString(
					R.string.control_signer,mDB.getPersonName(
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_ISSUER))),
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_ISSUE_TIME)))));
			tv = (TextView) view.findViewById(R.id.sender);
			tv.setText(Html.fromHtml(mRe.getString(
					R.string.control_publishor,mDB.getPersonName(
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_SENDER))),
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_SEND_TIME)))));
			Button b = (Button) view.findViewById(R.id.sure_close);
			mInfoId = info.getString(info
					.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_ID));
			Log.e("---------------mNoticeId----------------",mInfoId);
			final EditText et = (EditText)view.findViewById(R.id.statuses);
			final Button down = (Button)view.findViewById(R.id.ib_down);
			if(type==DBHelper.APP_TYPE_WORK_REPORT) et.setText(R.string.status_work_report);
			down.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					final ListView listView = (ListView)getLayoutInflater().inflate(R.layout.list, null);
					final Dialog dialog = new Dialog(CommonTabActivity.this);
					ArrayAdapter<CharSequence> adapter = null;
					if(type!=DBHelper.APP_TYPE_WORK_REPORT){
						adapter = ArrayAdapter.createFromResource(
			                CommonTabActivity.this, R.array.status, R.layout.spinner);
					}
					else{
						adapter = ArrayAdapter.createFromResource(
								CommonTabActivity.this, R.array.status2, R.layout.spinner);
					}
					listView.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							et.setText((CharSequence)listView.getItemAtPosition(position));
							dialog.dismiss();
						}
					});
			        listView.setAdapter(adapter);
			        dialog.setContentView(listView);
			        dialog.show();
				}
			});
			b.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mReplyContent = (String)et.getText().toString();
					mReplyTime = Tools.getCurrentTimeString();
					mPopupDialog.dismiss();
					isDialogShow = false;
					mDB.updateImportNotice(Integer.parseInt(mInfoId),mReplyContent,mReplyTime);
					mDB.insertUploadReply(mInfoId,mReplyContent,mReplyTime);
					Intent i = new Intent("action.push.finish");
			    	sendBroadcast(i);
				}
			});
			String webImage = info.getString(info.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_IMAGE_WEBURL));
			b = (Button)view.findViewById(R.id.btn_look);
			if(webImage!=null && !"".equals(webImage)){
				b.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mUrl = info.getString(info.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_IMAGE_WEBURL));
						new LoadImageTask().execute();
					}
				});
			}
			else{
				b.setVisibility(View.GONE);
			}
			mPopupDialog.setContentView(view);
			mPopupDialog.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					Log.e("---------onKeyDown-----------","-----------keyCode-"+keyCode+"---isDialogShow : " + String.valueOf(isDialogShow));
					if(keyCode == KeyEvent.KEYCODE_BACK){
						Log.e("---------KeyEvent.KEYCODE_BACK-----------","-----------KeyEvent.KEYCODE_BACK----isDialogShow : " + String.valueOf(isDialogShow));
						if(isDialogShow){
							View view = getLayoutInflater().inflate(R.layout.control_center_dialog, null);
							final EditText et = (EditText)view.findViewById(R.id.statuses);
							mReplyContent = (String)et.getText().toString();
							mReplyTime = Tools.getCurrentTimeString();
							mPopupDialog.dismiss();
							isDialogShow = false;
							mDB.updateImportNotice(Integer.parseInt(mInfoId),mReplyContent,mReplyTime);
							mDB.insertUploadReply(mInfoId,mReplyContent,mReplyTime);
							Intent i = new Intent("action.push.finish");
					    	sendBroadcast(i);
						}
					}
					return false;
				}
			});
			isDialogShow = true;
			mPopupDialog.show();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// if(keyCode == KeyEvent.KEYCODE_CALL && mBar!=null){
		// mBar.getBtnLeft().dispatchKeyEvent(new
		// KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_CALL));
		// return true;
		// }
		// if(keyCode == KeyEvent.KEYCODE_ENDCALL && mBar!=null){
		// mBar.getBtnRight().dispatchKeyEvent(new
		// KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENDCALL));
		// return true;
		// }
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopPush();
		if(mInfos.isFlipping()) mInfos.stopFlipping(); 
		mBottomBar.startFlipper();
		if(mReiceiver!=null) unregisterReceiver(mReiceiver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		new FetchOtherTask(this,mDB, new OnFetchOtherFinishedListener() {	
			@Override
			public void OnFinished(ArrayList<News> news, Game game, Weather weather) {
				if(news!=null && news.size()>0){
					for(News n : news){
						mInfos.addView(getNewsView(n));
						mInfos.startFlipping();
					}
				}
				else{
					mInfos.addView( mInflater.inflate(R.layout.news_item, null));
				}
				mBottomBar.setGame(game);
				mBottomBar.setWeather(weather);
				mBottomBar.startFlipper();
			}
		}).execute(mLocale);
		startReceiveMessage();
		startPush();
		mBottomBar.setMode(mHelper.getBoolean(CommonActivity.PERFERENCE_MODE));
		int language = mHelper.getInt(CommonActivity.PERFERENCE_LANGUAGE);
		if(mLocale!=language){
			mLocale = language;
			Intent i = new Intent(this, this.getClass());
			startActivity(i);
			finish();
		}
		
		mPopupCursor = mDB.nearlyNotice();
		if(mPopupCursor!=null&&mPopupCursor.getCount()>0){
			showDailog(mPopupCursor);
			mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_CLEAR, 1*1000);
		}
		
		new FetchOtherTask(CommonTabActivity.this, mDB, new OnFetchOtherFinishedListener() {	
			@Override
			public void OnFinished(ArrayList<News> news, Game game, Weather weather) {
				if(news!=null && news.size()>0){
					for(News n : news){
						mInfos.addView(getNewsView(n));
						mInfos.startFlipping();
					}
				}
				else{
					mInfos.addView( mInflater.inflate(R.layout.news_item, null));
				}
				mBottomBar.setGame(game);
				mBottomBar.setWeather(weather);
				mBottomBar.startFlipper();
			}
		}).execute(mLocale);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mPopupCursor!=null) mPopupCursor.close();
		if(mDB!=null) mDB.close();
		mNotificationManager.cancel(PROMPT_ID);
	}

	protected void initView() {
		mBuilder = new Builder(this).setTitle(R.string.tip);
		mBar = (Bar) findViewById(R.id.bar);
		mBottomBar = (BottomBar) findViewById(R.id.bottomBar);
		mInfos = (ViewFlipper) findViewById(R.id.infos);
		mInflater = getLayoutInflater();
		mPerson = mDB.getMeBySim();

		mBar.setOnBarClickListener(new OnBarClickListener() {

			@Override
			public void onClickRight() {
				
			}

			@Override
			public void onClickLeft() {
				Intent i = new Intent(CommonTabActivity.this,MainActivity.class);
				startActivity(i);
				finish();
			}
		});
		mBottomBar.setCallClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_DIAL);
				startActivity(i);
			}
		});
		mBottomBar.setSMSClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Tools.sendMsg(CommonTabActivity.this, "", "");
			}
		});
		mBottomBar.setConstactslickListener(new OnClickListener(){	
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(CommonTabActivity.this,MeReportActivity.class);
				startActivity(intent);
			}
		});
		mBottomBar.setModeClickListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(mHelper.getBoolean((CommonActivity.PERFERENCE_MODE))!=isChecked){
					if(isChecked){//振动
						mHelper.put(CommonActivity.PERFERENCE_MODE, true);
						mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
						mBuilder.setMessage(R.string.ringer_vibrate)
						.setNegativeButton(R.string.btn_sure, null)
						.show();
					}
					else{
						mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
						mHelper.put(CommonActivity.PERFERENCE_MODE, false);
						//设为震动+最大音量
						mAudioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), 0);
						mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM), 0);
						mAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
						
						
//						mHelper.put(CommonActivity.PERFERENCE_MODE, false);
//						mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
						mBuilder.setMessage(R.string.ringer_normal)
						.setNegativeButton(R.string.btn_sure, null)
						.show();
				}
				}
			}
		});
		 new FetchOtherTask(this,mDB, new OnFetchOtherFinishedListener() {	
				@Override
				public void OnFinished(ArrayList<News> news, Game game, Weather weather) {
					if(news!=null && news.size()>0){
						for(News n : news){
							mInfos.addView(getNewsView(n));
						}
					}
					else{
						mInfos.addView( mInflater.inflate(R.layout.news_item, null));
					}
					mInfos.startFlipping();
					mBottomBar.setGame(game);
					mBottomBar.setWeather(weather);
				}
			}).execute();
	}

	protected View getNewsView(final News news) {
		TextView tv = (TextView) mInflater.inflate(R.layout.news_item, null);
		tv.setCompoundDrawablesWithIntrinsicBounds(Tools.getIconByType(news.type), 0, 0, 0);
		tv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				Intent i = null;
//				switch(news.appType){
//					case DBHelper.APP_TYPE_IMPORT_NOTICE:
//						i = new Intent(CommonTabActivity.this, ImportNoticeActivity.class);
//						break;
//					case DBHelper.APP_TYPE_ME_REPORT:
//						i = new Intent(CommonTabActivity.this, MeReportActivity.class);
//						break;
//					case DBHelper.APP_TYPE_WORK_REPORT:
//						i = new Intent(CommonTabActivity.this, WorkReportActivity.class);
//						break;
//				}	
//				if(i!=null){
//					i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//					startActivity(i);
//				}
			}
		});
		String content = "";
		switch(news.appType){
			case DBHelper.APP_TYPE_IMPORT_NOTICE:
				content += getString(R.string.top_dialog_import_notice_title,getString(R.string.import_notice),news.sendTime);
				break;
			case DBHelper.APP_TYPE_ME_REPORT:
				content += getString(R.string.top_dialog_import_notice_title,getString(R.string.me_report),news.sendTime);
				break;
			case DBHelper.APP_TYPE_WORK_REPORT:
				content += getString(R.string.top_dialog_import_notice_title,getString(R.string.work_report),news.sendTime);
				break;
		}
		content += news.content;
		tv.setText(content);
		return tv;
	}
	
	public void closeDialog(){
		mPopupDialog.dismiss();
		isDialogShow = false;
	}
	
	protected Bar mBar;
	protected DBHelper mDB;
	protected BottomBar mBottomBar;
	protected Resources mRe;
	protected ProgressDialog mDialog;
	protected ViewFlipper mInfos;
	protected LayoutInflater mInflater;
	
	class LoadImageTask extends CommonTask<Void>{
		private Bitmap mBitmap;

		public LoadImageTask(){
			super(CommonTabActivity.this,getString(R.string.loadImage));
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			Log.e("-------------------url : ",mUrl);
			if(mUrl!=null&&!"".equals(mUrl)){
				String u = mRe.getString(R.string.url_img,mUrl);
				Log.e("-------------------u : ",u);
				mBitmap = HttpManager.getURLBitmap(u);
			}else{
				showPicture(false,null);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Log.e("-------------------bm : ",String.valueOf(mBitmap));
			if(mBitmap != null){
				showPicture(true,mBitmap);
			}else{
				showPicture(false,null);
			}
		}
	}
}
